/*
 * @Description: ws | wss connect
 * @Author: cy2020
 * @Date: 2022-02-25 09:36:14
 * @LastEditTime: 2022-02-25 19:10:11
 */
let WebSocketClient = require('websocket').client;
const { validatorUrl, strToHex } = require('../utils');

class WS {
    defaultConfig = {
        connectUrl: '', // 服务器地址
        deviceName: ``, // 设备信息
        productKeys: ``, //
        deviceSecret: ``,
        connectTimeout: 4000, // 超时时间
        keepalive: 60, // 设备与物联网平台建立保活连接时的心跳间隔时间
        clean: false, // 是否清除session 默认是
    };
    config = {}; // 配置项
    constructor(config) {
        this.client = new WebSocketClient()
        this.config = { ...this.defaultConfig, ...config };
        this.timer = null
        this.init()
        this.connect()
        this.connectFailed()
    }
    init() {
        let { connectUrl } = this.config;
        if (connectUrl == '' || connectUrl == null) {
            throw new Error('缺少服务器地址');
        }
        const result = validatorUrl(connectUrl);
        if (!result) {
            throw new Error('url不合法');
        }
        this.client.connect(connectUrl);
    }
    connect() {
        let _that = this
        if(_that.timer) clearInterval(this.timer)
        this.client.on('connect', function(connection) {
            console.log('WebSocket Client Connected');
            _that.message(connection)
            _that.error(connection)
            _that.close()
            _that.publish(connection)
            _that.timer = setInterval(() => _that.publish(connection), 2000)
        })
    }
    reconnect (_that) {
      _that.client.connect(_that.config.connectUrl);
    }
    connectFailed(){
        // 无法建立连接
        let _that = this
        this.client.on('connectFailed', function(error) {
            console.log('Websocket Connect ' + error.toString());
            // 重连
            _that.reconnect(_that)
        });
    }
    message (connection) {
        connection.on('message', function(message) {
            console.log("Received: '" + message.utf8Data + "'")
            strToHex(JSON.stringify(message.utf8Data));
        })
    }
    error(connection) {
        // 当连接出现错误
        let _that = this
        connection.on('error', function(error) {
            console.log("Connection Error: " + error.toString());
            if (connection.connected) {
                _that.reconnect(_that)
            }
        });
    }
    close () {
        let _that = this
        this.client.on('close', function() {
            console.log('Connection Closed');
            if(_that.timer) clearInterval(_that.timer)
        })
    }
    publish(connection) {
        if (connection.connected) {
            let number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString())
            console.log("Send: '" + number)
        }
    }

}

module.exports = WS;
